<?php
namespace app\admin\controller;
use think\Db;
class Ordertaobao extends Base
{   

    
    public function lists(){
        //ajax查询数据
        if( is_post() ){
            $page     = input('page');
            $keyword  = input('keyword');
            $min_time = input('min_time');
            $max_time = input('max_time');
            
            //原生态sql查询
            $sql = "
                select
                    [1]
                from
                    tb_order
                where 
                    1 = ?
                ";
            $param = [1];
            if ( !empty($keyword) ) {
                $sql .= " and s_shop_name like ?";
                $param[] = "%{$keyword}%";
            }
            if ( !empty($min_time) ) {
                $sql    .= " and t_creat_time >= ?";
                $param[] = strtotime($min_time);
            }
            if ( !empty($max_time) ) {
                $sql    .= " and t_creat_time <= ?";
                $param[] = strtotime($max_time);
            }
            //总条数
            $sql_count = str_replace("[1]", "count(*) as total", $sql);
            $total     = Db::query($sql_count, $param);
            $total     = $total[0]['total'];
            
            //分页数据
            $page_size   = c('page_size');     #分页条数
            $page        = com_cur_page($total, $page,  $page_size);   #当前页
			$page_data   = com_page_data($total, $page,  $page_size);   #分页原始数据
            
            //列表数据
			$start       = ($page - 1) * $page_size;
			$sql        .= " order by id desc limit $start, $page_size";
			$field       = "*";
			$sql_list    = str_replace("[1]", $field, $sql);
            $list        = Db::query($sql_list, $param);
            
            //格式数据
            foreach($list as $k => $v){                
                $list[$k]['t_creat_time']    =  com_format_time( $v['t_creat_time'] );
            }
			$com_body    = com_build_table($list, array(
                                "s_goods_name",
                                "s_ww_name", 
                                "s_cat_name", 
                                "s_shop_name", 
                                "s_goods_price", 
                                "s_goods_num", 
                                "l_media_name",
                                "o_order_no",
                                "o_order_type",
                                "o_deal_type",
                                "o_butie_type",
                                "o_butie_money",
                                "o_butie_percent",
                                "o_order_status",
                                "o_sr_percent",
                                "o_fc_percent",
                                "o_order_money",
                                "o_end_money",
                                "o_end_time",
                                "o_yj_percent",
                                "o_yj_money",
                                "t_creat_time",
                                ));
			$com_page    = com_build_page( $page_data );
			$data = array(
				"com_body"  => $com_body,
				"com_page"  => $com_page,
			);
			com_check(['data'=>$data]);
        }       
        $data = [
            'nav'       => ['淘宝订单管理', '列表'],
        ];
        return view('', $data);
    }

    
    //现在淘宝订单
    public function caiji(){
           header("Content-Type:text/html;charset=utf-8");
           ignore_user_abort();
           set_time_limit( 60 * 15 );
           $s = new \org\Snoopy();
           $s->accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
           $s->use_gzip = true;
           
           $tb_cookie = \app\common\model\Sys::get('alimama_cookie');
           $rs = explode(";", $tb_cookie);           
           $cookies = [];
           foreach($rs as $v){
               $val = explode("=", $v);
               if(isset($val[1])) $cookies[trim($val[0])] = $val[1];
           }
           $s->cookies  = $cookies;
           
           $this->host  = "pub.alimama.com";
           $this->referer = "";
           $this->agent   = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36";
           
           
           
           #订单时间段
           $s_time = date("Y-m-d",strtotime("-7 day")); 
           $e_time = date("Y-m-d");
           $url = "http://pub.alimama.com/report/getTbkPaymentDetails.json?spm=a219t.7664554.1998457203.62.BsMTdA&queryType=1&payStatus=&DownloadID=DOWNLOAD_REPORT_INCOME_NEW&startTime={$s_time}&endTime={$e_time}";
           $s->fetch($url);
           $rs = $s->results;
           preg_match('/阿里妈妈/', $rs, $out);
           if($out){
               com_error(['请重新登陆阿里妈妈， 并更新cookie!']);
               com_check();
           }else{
               $path = order_taobao($s->results, "{$s_time}_{$e_time}");
                
               #处理订单逻辑
               $url = "http://{$_SERVER['HTTP_HOST']}/other.php?type=readExcle&path=".urlencode($path);
               $rs  = json_decode(file_get_contents($url),true);
               // t($rs); 

               $otb = new \app\admin\model\OrderTaoBao();
               $otb->order($rs);


               
               
               #页面下载
               com_check(['data'=>"http://{$_SERVER['HTTP_HOST']}/".$path]);
           }
    }

    public function history(){
        $path = c('uploads')."ordertaobao/";
        $FilePath = opendir($path);
        $FileAndFolderAyy=array();
        $i=1;
        while (false !== ($filename = readdir($FilePath))) {
            if ($filename!="." && $filename!=".."){
                $i++;
                $FileAndFolderAyy[$i]['name'] = $filename;
                $FileAndFolderAyy[$i]['time'] = com_get_filetime($path.$filename);
                $FileAndFolderAyy[$i]['size'] = com_get_filesize($path.$filename);
            }
        
        }
        $data = [
            'list' => $FileAndFolderAyy, 
        ];
        return view('', $data);
    }
    
    public function down( $name=''){
        $path = "http://".$_SERVER['HTTP_HOST'].c('uploads')."ordertaobao/".$name;
        $config = [
            'data' =>$path,
            'suc' => [
                'js_action' => 'function.down_order',
            ],
        ];
        com_check($config);
    }
    
    
    
    /**
     * 清除数据
     */
    public function delete($name=""){
        unlink(c('uploads')."ordertaobao/".$name);
        com_check(['suc'=>['msg'=>'删除成功', 'js_action'=>'alert|f5']]);
    }
}